﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.Mvc;
using DHQGHN.PM2.Models;
using DHQGHN.PM2.Models.Online;

namespace DHQGHN.PM2.Controllers
{
    [Authorize]
    public class SurveyController : BaseController
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SurveyController));
        public ActionResult Index()
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
            ViewBag.ActiveMenus[106] = "active";
            ViewBag.ActiveMenus[140] = "active";
            ViewBag.Groups = GetProvince("-1", "1");

            return View();
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult StatisticsResult(StatisticsInfoModel obj)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetResult");
                    wc.Encoding = Encoding.UTF8;
                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                    string jsonData = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj);
                    string jsonResult = wc.UploadString(serviceUrl + "StatisticsService.svc" + "/" + "GetResult", "POST", jsonData);

                    List<InvestigationStatisticsModel> result =
                        JsonConvert.DeserializeObjectAsync<List<InvestigationStatisticsModel>>(jsonResult).Result;

                    return PartialView(result);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult ChartResult(StatisticsInfoModel obj)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetResult");
                    wc.Encoding = Encoding.UTF8;
                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                    string jsonData = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj);
                    string jsonResult = wc.UploadString(serviceUrl + "StatisticsService.svc" + "/" + "GetResult", "POST", jsonData);

                    List<InvestigationStatisticsModel> result =
                        JsonConvert.DeserializeObjectAsync<List<InvestigationStatisticsModel>>(jsonResult).Result;
                    //ViewBag.GeneralData = GetGeneralData();

                    return PartialView(result);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public JsonResult GetData(string code, string level)
        {
            try
            {
                if (level == "1")
                {
                    return Json(new SelectList(GetProvince(code, level), "Value", "Text"));
                }
                else if (level == "2")
                {
                    return Json(new SelectList(GetDistrict(code, level), "Value", "Text"));
                }
                else if (level == "3")
                {
                    return Json(new SelectList(GetCommune(code, level), "Value", "Text"));
                }

                return Json(new SelectList(GetArea(code), "Value", "Text"));
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public List<AdministrativeUnitModel> GetAdministrativeUnit(string code, string level)
        {
            try
            {
                List<AdministrativeUnitModel> areaList = new List<AdministrativeUnitModel>();

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByIdParentTablet");
                    wc.Encoding = Encoding.UTF8;
                    string UrlPath = string.Format("{0}{1}{2}/{3}", serviceUrl, "AdminUnitService.svc/GetByIdParentTablet/", code, level);
                    string areaDownload = wc.DownloadString(UrlPath);

                    areaList = JsonConvert.DeserializeObjectAsync<List<AdministrativeUnitModel>>(areaDownload).Result;

                    return areaList;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public List<SelectListItem> GetProvince(string code, string level)
        {
            try
            {
                List<AdministrativeUnitModel> dataItems = GetAdministrativeUnit(code, level);

                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = String.Empty,
                    Text = "-- Chọn tỉnh, thành phố --"
                });

                foreach (AdministrativeUnitModel area in dataItems)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = area.CODE.ToString(),
                        Text = area.ADM_NAME
                    });
                }
                return lstItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public List<SelectListItem> GetDistrict(string code, string level)
        {
            try
            {
                List<AdministrativeUnitModel> dataItems = GetAdministrativeUnit(code, level);

                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = String.Empty,
                    Text = "-- Chọn quận, huyện --"
                });

                foreach (AdministrativeUnitModel area in dataItems)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = FormatCode(area.CODE, area.DISTRICT_CODE),
                        Text = area.ADM_NAME
                    });
                }
                return lstItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public List<SelectListItem> GetCommune(string code, string level)
        {
            try
            {
                List<AdministrativeUnitModel> dataItems = GetAdministrativeUnit(code, level);

                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = String.Empty,
                    Text = "-- Chọn xã, phường --"
                });

                foreach (AdministrativeUnitModel area in dataItems)
                {
                    if (area.LEVELS == Convert.ToInt32(level))
                    {
                        lstItems.Add(new SelectListItem
                        {
                            //Value = area.COMMUNE_CODE.ToString(),
                            Value = FormatCode(area.CODE, area.COMMUNE_CODE),
                            Text = area.ADM_NAME
                        });
                    }
                }
                return lstItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public List<SelectListItem> GetArea(string code)
        {
            try
            {
                List<AreaModel> areaList = GetAreaByAdminCode(code);

                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = String.Empty,
                    Text = "-- Chọn địa bàn --"
                });

                foreach (AreaModel area in areaList)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = area.AREA_ID,
                        Text = area.AREA_NAME
                    });
                }

                return lstItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public List<AreaModel> GetAreaByAdminCode(string code)
        {
            try
            {
                List<AreaModel> areaList = new List<AreaModel>();

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByAdminCode");
                    wc.Encoding = Encoding.UTF8;
                    string UrlPath = string.Format("{0}GetByAdminCode/{1}", areaServiceUrl, code);
                    //string areaDownload = wc.DownloadString(areaServiceUrl + "GetByAdminCode" + "/" + code);
                    string areaDownload = wc.DownloadString(UrlPath);

                    areaList = JsonConvert.DeserializeObjectAsync<List<AreaModel>>(areaDownload).Result;

                    return areaList;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string FormatCode(string val1, string val2)
        {
            string result = val1 + ";" + val2;

            return result;
        }

        private DateTime GetDateTime(string date)
        {
            //string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
            //string sysUIFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;

            string[] arrDate = date.Split("/, -".ToCharArray());
            int day = int.Parse(arrDate[0]);
            int month = int.Parse(arrDate[1]);
            int year = int.Parse(arrDate[2]);

            DateTime dt = new DateTime(year, month, day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

            return dt;
        }
    }
}